<template>
  <div>
    <el-card class="mb-10">
      <CategorySelector :disabled="isEdit" />
    </el-card>
    <el-card>
      <div v-show="!isEdit">
        <el-button
          type="primary"
          :icon="Plus"
          class="mb-10"
          :disabled="!categoryStore.category3Id"
          @click="isEdit = true"
          >添加属性
        </el-button>
        <el-table :data="attrList" border>
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            property="attrName"
            width="280"
          ></el-table-column>
          <el-table-column label="属性值名称列表" width="600">
            <template #default="{ row, $index }">
              <el-tag
                class="mr-10"
                type="success"
                v-for="item in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <el-button
                type="warning"
                :icon="Edit"
                size="small"
                @click="editAttr(row)"
                title="修改"
              ></el-button>
              <el-popconfirm
                :title="`你确定删除[${row.attrName}]的属性名数据吗？`"
                @confirm="deleteAttr(row)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                    title="删除"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="isEdit">
        <el-form :inline="true">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrForm.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-form>
          <el-form-item class="mb-10">
            <el-button
              type="primary"
              :disabled="!attrForm.attrName"
              @click="addAttrVal"
              >添加属性值</el-button
            >
            <el-button @click="onCancelSave">取消</el-button>
          </el-form-item>
          <el-table :data="attrForm.attrValueList" border>
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="属性值名称">
              <template #default="{ row, $index }">
                <el-input
                  v-if="row.inputVisible"
                  ref="inputRef"
                  v-model="row.valueName"
                  size="small"
                  @blur="inputBlur(row, $index)"
                ></el-input>
                <div v-else @click="inputFocus(row)">{{ row.valueName }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row, $index }">
                <el-popconfirm
                  :title="`你确定删除[${row.valueName}]属性值吗？`"
                  @confirm="removeAttrVal(row, $index)"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      :icon="Delete"
                      size="small"
                      title="删除"
                    ></el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div class="mt-10">
          <el-button type="primary" @click="onSave">保存</el-button>
          <el-button @click="onCancelSave">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import { ElMessage, type InputInstance } from "element-plus";
import type { AttrModel, AttrValueModel } from "@/api/attr";
import attrApi from "@/api/attr";
import { useCategoryStore } from "@/stores/category";
import { cloneDeep } from "lodash";
const categoryStore = useCategoryStore();

//控制页面的显示和隐藏 和禁用
const isEdit = ref(false);
const attrList = ref<AttrModel[]>();
const inputRef = ref<InputInstance>();
//手机表单数据

const initAttrForm = () => ({
  attrName: "", //属性名
  attrValueList: [],
  categoryId: undefined, // 在保存之前校验一下去赋值(初始化的时候赋值也可以)
  categoryLevel: 3,
});
const attrForm = ref<AttrModel>(initAttrForm());

//添加属性值
const addAttrVal = () => {
  console.log(1);
  attrForm.value.attrValueList.push({
    valueName: "",
    inputVisible: true,
  });
  nextTick(() => {
    inputRef.value?.focus();
  });
  // console.log(attrForm.value.attrValueList);
};
//删除属性值
const removeAttrVal = (row: AttrValueModel, index: number) => {
  console.log(1);
  attrForm.value.attrValueList.splice(index, 1);
  ElMessage.success("删除成功");
};
//点击编辑数据回响  需要用到深度克隆
const editAttr = (row: AttrModel) => {
  attrForm.value = cloneDeep(row);
  isEdit.value = !isEdit.value;
};
//点击保存 手动校验 发送请求
const onSave = async () => {
  if (
    !(attrForm.value.attrName.trim() && attrForm.value.attrValueList.length)
  ) {
    ElMessage.error("[属性名] 和 [属性值列表] 必须有值");
    //手动校验通过  添加第三个id值  因为添加没有categoryId值
    return;
  }
  console.log(attrForm.value.attrValueList);
  attrForm.value.categoryId = categoryStore.category3Id;
  try {
    await attrApi.save(attrForm.value);
    await getList();
    ElMessage.success("添加成功");
    onCancelSave();
  } catch (e) {
    console.error(e);
    ElMessage.error("添加失败");
    return Promise.reject(e);
  }
};
//取消 清空表单返回主页菜单
const onCancelSave = () => {
  isEdit.value = !isEdit.value;
  attrForm.value = initAttrForm();
};

// 删除主界面数据
const deleteAttr = async (row: AttrModel) => {
  console.log(row.id);
  try {
    await attrApi.delete(row.id as number);
    ElMessage.success("删除成功");
    await getList();
  } catch (e) {
    console.error(e);
    ElMessage.error("删除失败");
  }
};

/*--------------------------失焦的处理获焦--------------------------------*/
//定义创建的为el-input类型
//当文本框失去焦点 触发的回调
const inputBlur = (row: AttrValueModel, index: number) => {
  //判断输入的值是否为空
  if (row.valueName) {
    //判断输入的值是否存在相同
    const isName = attrForm.value.attrValueList.some((item, inx) => {
      if (inx != index) {
        return item.valueName == row.valueName;
      }
    });
    if (isName) {
      attrForm.value.attrValueList.splice(index, 1);
      ElMessage.error("不能添加相同的属性！");
      return;
    }
  } else {
    attrForm.value.attrValueList.splice(index, 1);
    ElMessage.error("内容不能为空！");
  }
  row.inputVisible = false;
};
//当点击div文本标签  可以修改文本框内容
const inputFocus = (row: AttrValueModel) => {
  row.inputVisible = true;
  //input聚焦  存在异步操作 所以使用nextTicK
  nextTick(() => {
    inputRef.value?.focus();
  });
};
/*------------------------------------------------------------------------*/
//发送请求获取得到数据
const getList = async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  console.log(categoryStore);
  try {
    const result = await attrApi.getAttrInfoList(
      category1Id as number,
      category2Id as number,
      category3Id as number
    );
    attrList.value = result;
    // (attrList.value as any) = result;
  } catch (error) {
    console.error(error);
    ElMessage.error("获取平台属性列表失败");
  }
};
//监听获取的到第一级id的变化，列表展现数据
watch(
  () => categoryStore.category3Id,
  (newVal) => {
    if (!newVal) {
      attrList.value = [];
      return;
    }
    getList();
  },
  { immediate: true }
);
</script>

<style scoped lang="css"></style>
